package entity;

import server.HttpServlet;
import server.RequestProcessor;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.*;

public class Connector {
    private int port ;
    private HashMap<String , HttpServlet> servletMap;

    public Connector(int port, HashMap<String, HttpServlet> servletMap) {

        this.port = port;
        this.servletMap = servletMap;
    }

    public void start(){
        try {
            System.out.println("port:"+ port);
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("Minicat 开始监听："+port);
            // 定义一个线程池
            int corePoolSize = 10;
            int maximumPoolSize =50;
            long keepAliveTime = 100L;
            TimeUnit unit = TimeUnit.SECONDS;
            BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
            ThreadFactory threadFactory = Executors.defaultThreadFactory();
            RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
            ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                    corePoolSize,
                    maximumPoolSize,
                    keepAliveTime,
                    unit,
                    workQueue,
                    threadFactory,
                    handler
            );
            while (true){
                Socket socket = serverSocket.accept();
                RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap);
                threadPoolExecutor.execute(requestProcessor);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
/*public class Connector {
    private int port;
    private String hostName;
    private String appBase;
    private List<Context> contextList = new ArrayList<>();

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getHostName() {
        return hostName;
    }

    public void setHostName(String hostName) {
        this.hostName = hostName;
    }

    public String getAppBase() {
        return appBase;
    }

    public void setAppBase(String appBase) {
        this.appBase = appBase;
    }

    public List<Context> getContextList() {
        return contextList;
    }

    public void setContextList(List<Context> contextList) {
        this.contextList = contextList;
    }
}*/
